﻿using System.Text;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Interface;

namespace XuanXiang.Api.Admin.Middles
{
    public class Exception_Middle
    {
        private readonly IConfiguration _configuration;
        private readonly RequestDelegate _next;


        /// <summary>
        /// 异常处理中间件
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="next"></param>
        public Exception_Middle(IConfiguration configuration, RequestDelegate next)
        {
            _configuration = configuration;
            _next = next;


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="log_Service"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, I_Log_Service log_Service)
        {
            try {
                await _next(context);
            }
            catch (Exception ex)
            {
                string paras = "";
                if (context.Request.Method.ToUpper() == "GET")
                {
                    var keys = context.Request.Query.Keys;
                    foreach (var item in keys)
                    {
                        paras += $"{item}={context.Request.Query[item]};";
                    }
                }
                else
                {
                    var request = context.Request;
                    request.EnableBuffering();
                    if (request.Method.ToLower().Equals("post"))
                    {
                        request.Body.Seek(0, SeekOrigin.Begin);
                        using var reader = new StreamReader(request.Body, Encoding.UTF8);
                        paras = await reader.ReadToEndAsync();
                    }
                }

                //获取地址
                var path = _configuration["LogPath"];
                path += $"{DateTime.Now.ToString("yyyyMMdd")}.txt";

                var new_paras = "";
                if (paras.IndexOf("password") > -1) { 
                //将密码替换成*
                var index=paras.IndexOf("password");
                    new_paras = paras.Substring(index + 12);
                    var end_index = new_paras.IndexOf("\"");

                    new_paras = new_paras.Substring(end_index);
                    for (int i = 0; i < end_index; i++)
                    {
                        new_paras = "*" + new_paras;
                    }
                    paras = paras.Substring(0, index + 12) + new_paras;
                }


                //记录在记事本
                try {
                    var message = $"时间：{DateTime.Now.ToString()}\r\n" +
                      $"地址：{context.Request.Path}\r\n" +
                      $"类型：{context.Request.Method.ToUpper()}\r\n" +
                      $"参数：{paras}\r\n" +
                      $"错误：{ex.Message}\r\n\r\n";
                    //记录到本地文件
                    await System.IO.File.AppendAllTextAsync(path, message);
                } catch { 
                
                }

                //记录在数据库
                try {
                    log_Service.AddErrorLog(new Infrastructure.EFCore.MySql.SysError { 
                    
                        EId=Config.GUID(),
                        ECreateTime=DateTime.Now,
                        EMessage=ex.Message,
                        EMethod=context.Request.Method.ToUpper(),
                        EParams=paras.Length>999?paras.Substring(0,999):paras,
                        EUrl=context.Request.Path,
                    });
                
                }catch {
                    await System.IO.File.AppendAllTextAsync(path, $"时间：{DateTime.Now.ToString()}\r\n记录日志到数据库失败");
                }


                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("服务器内部错误");   



            }
        }
        }
}
